<template>
  <div class="personnel-process">
    <div class="page-title">数据处理</div>

    <!-- 处理控制面板 - 单行紧凑布局 -->
    <div class="page-card control-panel">
      <div class="control-content">
        <!-- 批次配置 -->
        <div class="control-item">
          <label>批次大小：</label>
          <el-input-number
            v-model="batchSize"
            :min="1"
            :max="100"
            controls-position="right"
            size="default"
          />
        </div>

        <!-- 待处理统计 -->
        <div class="control-item">
          <el-tag type="info" size="large">
            <span style="font-weight: 600;">待处理：{{ totalPending }} 条</span>
          </el-tag>
        </div>

        <!-- 处理进度 -->
        <div class="control-item progress-item" v-if="processStats.total > 0">
          <div class="progress-content">
            <div class="progress-info">
              <span class="progress-label">处理进度</span>
              <span class="progress-stats">
                已处理 <strong>{{ processStats.processed }}</strong> / 总计 <strong>{{ processStats.total }}</strong>
              </span>
              <span class="progress-percent">{{ processStats.percentage }}%</span>
            </div>
            <el-progress
              :percentage="processStats.percentage"
              :color="progressColor"
              :stroke-width="10"
              :show-text="false"
            />
          </div>
        </div>

        <!-- 操作按钮 - 横向排列 -->
        <div class="control-item action-buttons">
          <el-button
            type="primary"
            :icon="Tools"
            :loading="processing"
            @click="handleProcessBatch"
          >
            处理一批
          </el-button>
          <el-button
            type="success"
            :icon="Promotion"
            :loading="processing"
            @click="handleProcessAll"
          >
            处理所有
          </el-button>
          <el-button
            :icon="Refresh"
            @click="loadPendingList"
          >
            刷新列表
          </el-button>
        </div>
      </div>

      <!-- 处理结果 -->
      <el-alert
        v-if="processResult"
        :title="processResult.success ? '✓ 处理完成' : '✗ 处理失败'"
        :type="processResult.success ? 'success' : 'error'"
        :closable="true"
        @close="processResult = null"
        style="margin-top: 16px"
      >
        <div v-if="processResult.success">
          <span v-if="processResult.totalCount !== undefined">总数: {{ processResult.totalCount }} </span>
          <span v-if="processResult.successCount !== undefined">成功: {{ processResult.successCount }} </span>
          <span v-if="processResult.failCount !== undefined">失败: {{ processResult.failCount }}</span>
          <span v-if="processResult.message">{{ processResult.message }}</span>
        </div>
        <div v-else>
          {{ processResult.message }}
        </div>
      </el-alert>
    </div>

    <!-- 待处理列表 - 占满整个宽度 -->
    <div class="page-card list-panel">
      <div class="list-header">
        <h3>待处理列表</h3>
      </div>
      
      <el-table
        :data="pendingList"
        v-loading="loading"
        style="width: 100%"
        stripe
        :height="570"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column label="头像" width="80" align="center">
          <template #default="{ row }">
            <el-avatar
              v-if="row.avatar_url"
              :src="row.avatar_url"
              :size="45"
              fit="cover"
            >
              <template #error>
                <el-icon><User /></el-icon>
              </template>
            </el-avatar>
            <el-avatar v-else :size="45">
              <el-icon><User /></el-icon>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="180" show-overflow-tooltip />
        <el-table-column prop="position" label="岗位" min-width="220" show-overflow-tooltip />
        <el-table-column prop="rank" label="军衔" width="130" />
        <el-table-column label="数据来源" width="130" show-overflow-tooltip>
          <template #default="{ row }">
            <a 
              v-if="row.data_source" 
              :href="row.data_source" 
              target="_blank"
              class="data-source-link"
              :title="row.data_source"
            >
              {{ truncateUrl(row.data_source, 15) }}
            </a>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="简介预览" min-width="250">
          <template #default="{ row }">
            <div 
              class="biography-preview clickable"
              @click="showBiographyDetail(row)"
              title="点击查看完整简介"
            >
              <span>{{ row.biography?.substring(0, 80) || '无简介' }}{{ row.biography?.length > 80 ? '...' : '' }}</span>
              <el-icon class="view-icon" v-if="row.biography"><View /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              :loading="processing"
              @click="handleProcessSingle(row.id)"
            >
              处理
            </el-button>
            <el-button
              type="danger"
              size="small"
              :loading="deleting === row.id"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalPending"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 简介详情弹窗 -->
    <el-dialog
      v-model="biographyDialogVisible"
      :title="`${currentRecord?.name || ''} - 完整简介`"
      width="70%"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <div class="biography-detail">
        <div class="biography-info">
          <el-tag v-if="currentRecord?.position" type="info">{{ currentRecord.position }}</el-tag>
          <el-tag v-if="currentRecord?.rank" type="success">{{ currentRecord.rank }}</el-tag>
        </div>
        <el-divider />
        <div class="biography-content">
          {{ currentRecord?.biography || '无简介内容' }}
        </div>
        <el-divider />
        <div class="biography-meta">
          <span><strong>ID:</strong> {{ currentRecord?.id }}</span>
          <span v-if="currentRecord?.data_source">
            <strong>数据来源:</strong> 
            <a :href="currentRecord.data_source" target="_blank" class="data-source-link">
              {{ currentRecord.data_source }}
            </a>
          </span>
        </div>
      </div>
      <template #footer>
        <el-button @click="biographyDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleProcessSingle(currentRecord?.id)">
          立即处理
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Tools, Promotion, Refresh, User, View } from '@element-plus/icons-vue'
import { personnelApi } from '@/api/personnel'

const batchSize = ref(10)
const processing = ref(false)
const loading = ref(false)
const deleting = ref(null) // 记录当前正在删除的ID
const processResult = ref(null)
const pendingList = ref([])
const totalPending = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 简介详情弹窗
const biographyDialogVisible = ref(false)
const currentRecord = ref(null)

// 处理进度统计
const processStats = ref({
  total: 0,        // 总记录数（导入时的总数）
  processed: 0,    // 已处理数量
  pending: 0,      // 待处理数量
  percentage: 0    // 完成百分比
})

// 进度条颜色（根据完成度变化）
const progressColor = computed(() => {
  const percentage = processStats.value.percentage
  if (percentage < 30) return '#909399'
  if (percentage < 60) return '#409eff'
  if (percentage < 90) return '#67c23a'
  return '#67c23a'
})

// 加载待处理列表
const loadPendingList = async () => {
  loading.value = true
  try {
    const result = await personnelApi.getPendingList(currentPage.value, pageSize.value)
    if (result.success) {
      pendingList.value = result.data
      totalPending.value = result.total  // 使用total字段作为总数
      currentPage.value = result.page
    }
    
    // 同时加载统计信息
    await loadProcessStatistics()
  } catch (error) {
    ElMessage.error('加载失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 加载处理统计信息
const loadProcessStatistics = async () => {
  try {
    const result = await personnelApi.getProcessStatistics()
    if (result.success) {
      processStats.value = {
        total: result.total,
        processed: result.processed,
        pending: result.pending,
        percentage: result.percentage
      }
    }
  } catch (error) {
    console.error('加载统计信息失败:', error.message)
  }
}

// 页码改变
const handlePageChange = (page) => {
  currentPage.value = page
  loadPendingList()
}

// 每页数量改变
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1  // 重置到第一页
  loadPendingList()
}

// 截断URL显示
const truncateUrl = (url, maxLength = 20) => {
  if (!url) return ''
  
  // 移除协议前缀
  let displayUrl = url.replace(/^https?:\/\//, '')
  
  // 如果超过最大长度，进行截断
  if (displayUrl.length > maxLength) {
    return displayUrl.substring(0, maxLength) + '...'
  }
  
  return displayUrl
}

// 处理一批
const handleProcessBatch = async () => {
  if (pendingList.value.length === 0) {
    ElMessage.warning('没有待处理的数据')
    return
  }

  processing.value = true
  processResult.value = null

  try {
    const result = await personnelApi.processBatch(batchSize.value)
    processResult.value = result

    if (result.success) {
      if (result.totalCount === 0) {
        ElMessage.info('没有待处理的数据')
      } else {
        ElMessage.success(`处理完成: 成功 ${result.successCount}, 失败 ${result.failCount}`)
      }
      await loadPendingList()
    }
  } catch (error) {
    ElMessage.error('处理失败: ' + error.message)
  } finally {
    processing.value = false
  }
}

// 处理所有
const handleProcessAll = async () => {
  if (pendingList.value.length === 0) {
    ElMessage.warning('没有待处理的数据')
    return
  }

  await ElMessageBox.confirm(
    `确定要处理所有待处理数据吗？这可能需要较长时间。`,
    '确认',
    {
      type: 'warning'
    }
  )

  processing.value = true
  processResult.value = null

  try {
    const result = await personnelApi.processAll(batchSize.value)
    processResult.value = result

    if (result.success) {
      ElMessage.success(result.message || '处理任务已启动')
      setTimeout(() => {
        loadPendingList()
      }, 3000)
    }
  } catch (error) {
    ElMessage.error('处理失败: ' + error.message)
  } finally {
    processing.value = false
  }
}

// 处理单条
const handleProcessSingle = async (id) => {
  processing.value = true
  try {
    const result = await personnelApi.processSingle(id)
    if (result.success) {
      ElMessage.success(`处理成功: ${result.name}`)
      await loadPendingList()
    }
  } catch (error) {
    ElMessage.error('处理失败: ' + error.message)
  } finally {
    processing.value = false
  }
}

// 删除记录
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 "${row.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )

    deleting.value = row.id
    try {
      const result = await personnelApi.deleteRecord(row.id)
      if (result.success) {
        ElMessage.success(`删除成功: ${result.name}`)
        await loadPendingList()
      } else {
        ElMessage.error(result.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败: ' + error.message)
    } finally {
      deleting.value = null
    }
  } catch {
    // 用户取消删除
  }
}

// 显示简介详情
const showBiographyDetail = (row) => {
  currentRecord.value = row
  biographyDialogVisible.value = true
}

onMounted(() => {
  loadPendingList()
})
</script>

<style lang="scss" scoped>
.personnel-process {
  // 控制面板 - 单行紧凑布局
  .control-panel {
    margin-bottom: 20px;

    .control-content {
      display: flex;
      align-items: center;
      gap: 24px;
      flex-wrap: wrap;

      .control-item {
        display: flex;
        align-items: center;
        gap: 8px;

        label {
          font-size: 14px;
          color: #606266;
          white-space: nowrap;
        }

        &.progress-item {
          flex: 1;
          min-width: 300px;
          max-width: 500px;
        }

        &.action-buttons {
          margin-left: auto;
          gap: 12px;
        }
      }
    }

    // 进度条样式
    .progress-content {
      width: 100%;
      
      .progress-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
        font-size: 13px;

        .progress-label {
          color: #606266;
          font-weight: 500;
        }

        .progress-stats {
          color: #909399;
          flex: 1;
          margin: 0 12px;

          strong {
            color: #409eff;
            font-weight: 600;
          }
        }

        .progress-percent {
          color: #409eff;
          font-weight: 600;
          font-size: 16px;
        }
      }

      :deep(.el-progress__text) {
        display: none;
      }
    }
  }

  // 列表面板
  .list-panel {
    .list-header {
      margin-bottom: 16px;
      
      h3 {
        margin: 0;
      }
    }

    .biography-preview {
      color: #606266;
      font-size: 13px;
      line-height: 1.5;

      &.clickable {
        cursor: pointer;
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 4px 8px;
        border-radius: 4px;
        transition: all 0.2s;

        &:hover {
          background-color: #f5f7fa;
          color: #409eff;

          .view-icon {
            color: #409eff;
          }
        }

        .view-icon {
          color: #909399;
          font-size: 14px;
          transition: color 0.2s;
        }
      }
    }

    .data-source-link {
      color: #409eff;
      text-decoration: none;
      
      &:hover {
        color: #66b1ff;
        text-decoration: underline;
      }
    }

    .pagination-container {
      margin-top: 16px;
      display: flex;
      justify-content: center;
    }
  }

  // 响应式布局
  @media (max-width: 1200px) {
    .control-panel .control-content {
      flex-direction: column;
      align-items: stretch;
      gap: 16px;

      .control-item {
        justify-content: space-between;

        &.action-buttons {
          margin-left: 0;
          justify-content: flex-start;
        }
      }
    }
  }

  // 简介详情弹窗样式
  .biography-detail {
    .biography-info {
      display: flex;
      gap: 12px;
      flex-wrap: wrap;
    }

    .biography-content {
      max-height: 500px;
      overflow-y: auto;
      padding: 16px;
      background-color: #f5f7fa;
      border-radius: 4px;
      font-size: 14px;
      line-height: 1.8;
      color: #303133;
      white-space: pre-wrap;
      word-break: break-word;
    }

    .biography-meta {
      display: flex;
      gap: 24px;
      flex-wrap: wrap;
      font-size: 13px;
      color: #606266;

      span {
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .data-source-link {
        color: #409eff;
        text-decoration: none;
        word-break: break-all;

        &:hover {
          color: #66b1ff;
          text-decoration: underline;
        }
      }
    }
  }

  // 全局样式
  :deep(.el-alert) {
    p, span {
      margin: 0 8px 0 0;
      display: inline;
    }
  }

  :deep(.el-table) {
    .el-table__header {
      font-weight: 600;
    }

    // 头像列样式
    .el-avatar {
      border: 2px solid #e4e7ed;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);

      &:hover {
        border-color: #409eff;
      }
    }

    // 操作按钮样式
    .el-button + .el-button {
      margin-left: 8px;
    }
  }
}
</style>

